<template>
	<div>
		<el-dialog
			:title="title"
			:visible.sync="visible"
			:close-on-click-modal="false"
			append-to-body
			width="60%"
			:before-close="dialogBeforeClose"
			@closed="handlerClosed"
		>
			<el-form
				ref="form"
				:model="formData"
				:rules="rules"
				label-width="80px"
				:inline="false"
				size="normal"
			>
				<el-row>
					<el-col :span="12">
						<el-form-item label="医生工号" prop="jobNumber">
							<el-input
								v-model="formData.jobNumber"
								clearable
								@change="jobNumberSelectOne"
							/>
						</el-form-item>
						<el-form-item
							class="doctorIconClass"
							label="医生头像"
							prop="doctorIcon"
						>
							<el-upload
								class="avatar-uploader"
								:action="uploadFileUrl"
								:show-file-list="false"
								:data="paramsData"
								:on-success="handleSuccess"
								:before-upload="beforeUploadPicture"
								:headers="headers"
							>
								<img v-if="imageUrl" :src="imageUrl" class="avatar" />
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="医生名称" prop="doctorName">
							<el-input v-model="formData.doctorName" clearable />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="证件类型" prop="idTypeCode">
							<el-select
								v-model="formData.idTypeCode"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in idTypeCodeList"
									:key="item.value"
									:label="item.display"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="证件号码" prop="idCode">
							<el-input
								v-model="formData.idCode"
								:disabled="idCodeFlag"
								clearable
							/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="性别" prop="sexCode">
							<el-select
								v-model="formData.sexCode"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in sexCodeList"
									:key="item.value"
									:label="item.display"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="民族" prop="nation">
							<el-select
								v-model="formData.nation"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in nationList"
									:key="item.value"
									:label="item.display"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="婚姻状态" prop="marriageStatus">
							<el-select
								v-model="formData.marriageStatus"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in marriageStatusList"
									:key="item.value"
									:label="item.display"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="生育状态" prop="birthCode">
							<el-select
								v-model="formData.birthCode"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in birthCodeList"
									:key="item.value"
									:label="item.display"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="出生日期" prop="birthdayDate">
							<el-date-picker
								v-model="formData.birthdayDate"
								type="date"
								placeholder="选择日期"
								clearable
							>
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="年龄">
							<el-input v-model="formData.age" disabled clearable />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="国籍" prop="countryCode">
							<el-select
								v-model="formData.countryCode"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in countryCodeList"
									:key="item.value"
									:label="item.display"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="联系电话" prop="doctorTelephone">
							<el-input v-model="formData.doctorTelephone" clearable />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="职称" prop="doctorTitle">
							<el-select
								v-model="formData.doctorTitle"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in doctorTitleList"
									:key="item.value"
									:label="item.display"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="执业类别" prop="doctorPracticeType">
							<el-select
								v-model="formData.doctorPracticeType"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in doctorPracticeTypeList"
									:key="item.value"
									:label="item.display"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="执业范围" prop="doctorPracticeRange">
							<el-select
								v-model="formData.doctorPracticeRange"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in doctorPracticeRangeList"
									:key="item.value"
									:label="item.display"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="所属科室" prop="deptId">
							<el-select
								v-model="formData.deptId"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in deptList"
									:key="item.id"
									:label="item.orgName"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="是否启用" prop="whetherEnable">
							<el-select
								v-model="formData.whetherEnable"
								placeholder="请选择"
								clearable
							>
								<el-option
									v-for="item in whetherEnableList"
									:key="item.value"
									:label="item.display"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="擅长方向" prop="doctorMajor">
							<el-input
								v-model="formData.doctorMajor"
								type="textarea"
								:rows="2"
								clearable
							/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="医生简介" prop="briefIntroduction">
							<el-input
								v-model="formData.briefIntroduction"
								type="textarea"
								:rows="4"
								clearable
							/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item>
					<el-button type="primary" size="medium" @click="onSubmit">
						确定
					</el-button>
					<el-button size="medium" @click="handlerCancel"> 取消 </el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
import { getDoctorModel } from '@/http/doctor'
import { fileURLConfig, delImageUpload } from '@/http/upLoad'
import { getInfoByidCard } from '@/utils'
export default {
	props: {
		doctorData: {
			type: Object,
			default: () => {
				return {}
			},
		},
		visible: {
			type: Boolean,
			default: false,
		},
		title: {
			type: String,
			default: '',
		},
		doctorDialogType: {
			type: String,
			default: '',
		},
		sexCodeList: {
			type: Array,
			default: () => {
				return []
			},
		},
		doctorTitleList: {
			type: Array,
			default: () => {
				return []
			},
		},
		doctorPracticeTypeList: {
			type: Array,
			default: () => {
				return []
			},
		},
		doctorPracticeRangeList: {
			type: Array,
			default: () => {
				return []
			},
		},
		whetherEnableList: {
			type: Array,
			default: () => {
				return []
			},
		},
		deptList: {
			type: Array,
			default: () => {
				return []
			},
		},
	},
	data() {
		var jobNumberValidator = this.jobNumberSelectOne
		var idCodeValidator = this.idCodeSelectOne
		return {
			idCodeFlag: true,
			doctorIcon: '',
			relativeFolderImageUrl: '',
			imageUrl: '',
			oldImageUrl: '',
			uploadFileUrl: fileURLConfig.uploadPicture,
			paramsData: {
				folderName: fileURLConfig.uploadDoctorFolderName,
			},
			nationList: [],
			marriageStatusList: [],
			birthCodeList: [],
			idTypeCodeList: [],
			countryCodeList: [],
			rules: {
				jobNumber: [
					{ required: true, message: '请输入医生工号', trigger: 'blur' },
					{ validator: jobNumberValidator, trigger: 'blur' },
				],
				doctorName: [
					{ required: true, message: '请输入医生名称', trigger: 'blur' },
				],
				sexCode: [{ required: true, message: '请选择性别', trigger: 'blur' }],
				nation: [{ required: true, message: '请选择民族', trigger: 'blur' }],
				marriageStatus: [
					{ required: true, message: '请选择婚姻状态', trigger: 'blur' },
				],
				birthCode: [
					{ required: true, message: '请选择生育状态', trigger: 'blur' },
				],
				idTypeCode: [
					{ required: true, message: '请选择证件类型', trigger: 'blur' },
				],
				idCode: [
					{ required: true, message: '请输入证件号码', trigger: 'blur' },
					{ validator: idCodeValidator, trigger: 'blur' },
				],
				birthdayDate: [
					{ required: true, message: '请选择出生日期', trigger: 'blur' },
				],
				doctorTelephone: [
					{ required: true, message: '请输入联系电话', trigger: 'blur' },
					{
						pattern:
							/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/,
						message: '目前只支持中国大陆的手机号码',
					},
				],
				doctorTitle: [
					{ required: true, message: '请选择职称', trigger: 'blur' },
				],
				doctorPracticeType: [
					{ required: true, message: '请选择执业类别', trigger: 'blur' },
				],
				doctorPracticeRange: [
					{ required: true, message: '请选择执业范围', trigger: 'blur' },
				],
				whetherEnable: [
					{ required: true, message: '请选择是否启用', trigger: 'blur' },
				],
				countryCode: [
					{ required: true, message: '请选择国籍', trigger: 'blur' },
				],
				deptId: [{ required: true, message: '请选择科室', trigger: 'blur' }],
			},
		}
	},
	computed: {
		formData() {
			return this.doctorData
		},
		headers() {
			let token = JSON.parse(window.localStorage.getItem('userMsg')).token
			return {
				Authorization: token,
			}
		},
	},
	watch: {
		async visible(isVisible) {
			if (isVisible) {
				this.imageUrl = this.formData.doctorIcon
				if (this.doctorDialogType == '2') {
					this.oldImageUrl = this.formData.doctorIcon
				}
				if (this.formData.idTypeCode && this.formData.idTypeCode != '') {
					this.idCodeFlag = false
				} else {
					this.idCodeFlag = true
					this.formData.idCode = ''
				}
				// 民族
				this.nationList = await this.$parent.getSysDataDictList(
					'RC_NATION_DICT',
				)
				// 国籍 COUNTRY_DICT
				this.countryCodeList = await this.$parent.getSysDataDictList(
					'COUNTRY_DICT',
				)
				// 婚姻状态
				this.marriageStatusList = await this.$parent.getSysDataDictList(
					'RC_MARRIAGE_DICT',
				)
				// 生育状态
				this.birthCodeList = await this.$parent.getSysDataDictList(
					'RC_BIRTH_DICT',
				)
				// 身份证类型
				this.idTypeCodeList = await this.$parent.getSysDataDictList(
					'RC_IDENTITY_DICT',
				)
			}
		},
		'formData.idTypeCode': function (val) {
			if (val && val != '') {
				this.idCodeFlag = false
			} else {
				this.idCodeFlag = true
				this.formData.idCode = ''
			}
		},
		'formData.idCode': function (val) {
			if (val && val != '') {
				let obj = getInfoByidCard(val)
				if (obj) {
					this.formData.age = obj.age
					this.formData.birthdayDate = obj.birth
					this.formData.sexCode = obj.sex + ''
				}
			}
		},
	},
	methods: {
		jobNumberSelectOne(rule, value, callback) {
			if (value) {
				getDoctorModel({
					jobNumber: value,
					delFlag: '0',
				}).then(({ data }) => {
					if (data?.head?.code == 200) {
						if (Object.keys(data?.data || {}).length > 0) {
							if (this.formData.id) {
								if (this.formData.id != data.data.id) {
									callback(new Error('该工号已经存在'))
								} else {
									callback()
								}
							} else {
								callback(new Error('该工号已经存在'))
							}
						} else {
							callback()
						}
					}
				})
			}
		},
		idCodeSelectOne(rule, value, callback) {
			if (value) {
				getDoctorModel({
					idTypeCode: this.formData.idTypeCode,
					idCode: value,
					delFlag: '0',
				}).then(({ data }) => {
					if (data?.head?.code == 200) {
						if (Object.keys(data?.data || {}).length > 0) {
							if (this.formData.id) {
								if (this.formData.id != data.data.id) {
									callback(new Error('该证件号已经存在'))
								} else {
									callback()
								}
							} else {
								callback(new Error('该证件号已经存在'))
							}
						} else {
							callback()
						}
					}
				})
			}
		},
		// 文件上传前置方法
		beforeUploadPicture(file) {
			const isImage =
				file.type === 'image/png' ||
				file.type === 'image/jpg' ||
				file.type === 'image/jpeg'
			const isLt2M = file.size < 1024 * 1024 * 2
			if (!isImage) {
				this.$message.error('上传只能是png,jpg格式!')
			}
			if (!isLt2M) {
				this.$message.error('上传图片大小不能超过 2MB!')
			}
			return isImage && isLt2M
		},
		handleSuccess(res, file) {
			this.imageUrl = URL.createObjectURL(file.raw)
			if (file.response.head.code == '200') {
				this.doctorIcon = file.response.data[0].httpImageUrl
			}
			if (this.relativeFolderImageUrl) {
				if (this.doctorDialogType == '1') {
					delImageUpload({
						imagePath: this.relativeFolderImageUrl,
					}).then(({ data }) => {
						if (data.head.code == '200') {
							this.relativeFolderImageUrl =
								file.response.data[0].relativeFolderImageUrl
						}
					})
				} else {
					if (this.oldImageUrl != this.relativeFolderImageUrl) {
						delImageUpload({
							imagePath: this.relativeFolderImageUrl,
						}).then(({ data }) => {
							if (data.head.code == '200') {
								this.relativeFolderImageUrl =
									file.response.data[0].relativeFolderImageUrl
							}
						})
					}
				}
			} else {
				this.relativeFolderImageUrl =
					file.response.data[0].relativeFolderImageUrl
			}
		},
		dialogBeforeClose() {
			this.$emit('update:visible', false)
		},
		handlerClosed() {
			if (this.doctorIcon) {
				delImageUpload({
					imagePath: this.relativeFolderImageUrl,
				}).then(({ data }) => {
					if (data.head.code == '200') {
						this.imageUrl = ''
						this.relativeFolderImageUrl = ''
					}
				})
			}
			this.idCodeFlag = true
			this.doctorIcon = ''
			this.$emit('update:doctorData', {
				deptId: '',
				jobNumber: '',
				doctorName: '',
				doctorIcon: '',
				sexCode: '',
				nation: '1',
				marriageStatus: '',
				birthCode: '',
				birthdayDate: '',
				countryCode: 'CN',
				idTypeCode: '1',
				idCode: '',
				doctorTelephone: '',
				doctorTitle: '',
				doctorPracticeType: '',
				doctorPracticeRange: '',
				doctorMajor: '',
				briefIntroduction: '',
				whetherEnable: '0',
			})
			this.handlerResetFields()
		},
		onSubmit() {
			this.$refs.form.validate(valid => {
				if (valid) {
					// 如果是修改删除原图片
					if (this.doctorDialogType != '1') {
						if (this.oldImageUrl) {
							let delOldImageUrl = this.oldImageUrl.split('file/')[1]
							delImageUpload({
								imagePath: delOldImageUrl,
							}).then(({ data }) => {
								if (data.head.code == '200') {
									this.imageUrl = ''
									this.relativeFolderImageUrl = ''
								}
							})
						}
					}
					this.formData.doctorIcon = this.doctorIcon
					this.$emit('submit', this.formData, this.doctorDialogType)
					this.doctorIcon = ''
					this.handlerCancel()
				} else {
					return false
				}
			})
		},
		handlerCancel() {
			this.handlerResetFields()
			this.dialogBeforeClose()
			this.handlerClosed()
		},
		handlerResetFields() {
			this.$nextTick(() => {
				this.$refs['form'].clearValidate()
			})
		},
	},
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 100px;
	height: 100px;
	line-height: 100px;
	text-align: center;
}
.avatar {
	width: 100px;
	height: 100px;
	display: block;
}
.doctorIconClass {
	position: absolute;
	top: 0;
	left: 51%;
}
</style>
